/**
 * 
 */
package eu.jakubiak.mcc.request;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import eu.jakubiak.mcc.enums.Status;
import eu.jakubiak.mcc.protocol.Protocol;

/**
 * @author Antek
 * 
 */
@Deprecated
public class Request implements IRequest {
    /**
     * Logger
     */
    private static final Logger logger = LoggerFactory
            .getLogger(Request.class);

    /**
     * Protocol implementation
     */
    private Protocol protocol;

    public Protocol getProtocol() {
        return protocol;
    }

    public void setProtocol(Protocol protocol) {
        this.protocol = protocol;
    }

    /*
     * (non-Javadoc)
     * 
     * @see biz.jakubiak.mc.IMcRequest#begin(java.lang.String, java.lang.String,
     * java.lang.String, java.lang.String)
     */
    public String begin(String fileUrl, String format, String quality,
            String statusUrl) {
        String urlString = protocol.createUrlForBeginConversion(fileUrl,
                format, quality, statusUrl);
        logger.trace("Sending begin request: {}", urlString);
        URL url;
        try {
            url = new URL(urlString);
        } catch (MalformedURLException e) {
            logger.error("Error in URL address: {}", urlString);
            throw new RuntimeException(e);
        }
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url
                    .openStream()));
            String line;
            while ((line = in.readLine()) != null) {
                // str is one line of text; readLine() strips the newline
                // character(s)
                String key = protocol.parseBeginResponseAndGetKey(line);
                if (key != null) {
                    logger.debug("New MultimediaConversion: key={}", key);
                    while ((line = in.readLine()) != null) {}
                    in.close();
                    return key;
                }
            }
            in.close();
        } catch (IOException e) {
            logger.error("Error processing MultimediaConversion begin request",
                    e);
            throw new RuntimeException(e);
        }
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see biz.jakubiak.mc.IMcRequest#getStatus(java.lang.String)
     */
    public Status getStatus(String key) {
        String urlString = protocol.createUrlForStatus(key);
        logger.trace("Sending status request: {}", urlString);
        URL url;
        try {
            url = new URL(urlString);
        } catch (MalformedURLException e) {
            logger.error("Error in URL address: {}", urlString);
            throw new RuntimeException(e);
        }
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url
                    .openStream()));
            String line;
            while ((line = in.readLine()) != null) {
                // str is one line of text; readLine() strips the newline
                // character(s)
                Status status = protocol
                        .parseStatusResponseAndGetStatus(line);
                if (status != null) {
                    logger.debug("Current status={} for key={}", status, key);
                    while ((line = in.readLine()) != null) {}
                    in.close();
                    return status;
                }
            }
            in.close();
        } catch (IOException e) {
            logger.error(
                    "Error processing MultimediaConversion status request", e);
            throw new RuntimeException(e);
        }
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see biz.jakubiak.mc.IMcRequest#getResult(java.lang.String)
     */
    public byte[] getResult(String key) {
        String urlString = protocol.createUrlForResult(key);
        logger.trace("Sending result request: {}", urlString);
        URL url;
        try {
            url = new URL(urlString);
        } catch (MalformedURLException e) {
            logger.error("Error in URL address: {}", urlString);
            throw new RuntimeException(e);
        }
        try {
            return inputStreamToBytes(url.openStream());
        } catch (IOException e) {
            logger
                    .error("Error processing MultimediaConversion result request",
                            e);
            throw new RuntimeException(e);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see biz.jakubiak.mc.IMcRequest#getThumb(java.lang.String)
     */
    public byte[] getThumb(String key) {
        String urlString = protocol.createUrlForThumb(key);
        logger.trace("Sending thumb request: {}", urlString);
        URL url;
        try {
            url = new URL(urlString);
        } catch (MalformedURLException e) {
            logger.error("Error in URL address: {}", urlString);
            throw new RuntimeException(e);
        }
        try {
            return inputStreamToBytes(url.openStream());
        } catch (IOException e) {
            logger
                    .error("Error processing MultimediaConversion thumb request",
                            e);
            throw new RuntimeException(e);
        }
    }

    /**
     * Get bytes from input stream
     * 
     * @param in
     * @return
     * @throws IOException
     */
    private byte[] inputStreamToBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) >= 0) {
            out.write(buffer, 0, len);
        }
        out.close();
        in.close();
        return out.toByteArray();
    }
    

    /**
     * CRON
     */
    public String cron() {
        String urlString = protocol.getRootUrl() + "/cron";
        logger.trace("Sending cron request: {}", urlString);
        URL url;
        try {
            url = new URL(urlString);
        } catch (MalformedURLException e) {
            logger.error("Error in URL address: {}", urlString);
            throw new RuntimeException(e);
        }
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url
                    .openStream()));
            String line;
            while ((line = in.readLine()) != null) {
            	sb.append(line);
            }
            in.close();
        } catch (IOException e) {
            logger.error("Error processing MultimediaConversion begin request",
                    e);
            throw new RuntimeException(e);
        }
        return sb.toString();
    }
    
}
